package com.chen.palmar.project.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.constant.AppConstant;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoTabLayout;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.common.widget.view.SquareImageView;
import com.chen.palmar.entity.SearchEntity;
import com.chen.palmar.project.agency.AgencyDetailActivity;
import com.chen.palmar.project.producer.ProducerDetailActivity;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * @author Chen
 * @date 2018/1/9
 * 功能描述：
 */

public class SearchListActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.rv_collection_list)
    RecyclerView rvCollectionList;
    @Bind(R.id.tab_detail)
    AutoTabLayout tabDetail;
    @Bind(R.id.et_search)
    EditText etSearch;
    private SearchEntity entity;
    private BaseQuickAdapter<SearchEntity.DataBean.ViewArticleBean, BaseViewHolder> adapterInfo;
    private BaseQuickAdapter<SearchEntity.DataBean.StoreListBean, BaseViewHolder> adapterStore;
    private BaseQuickAdapter<SearchEntity.DataBean.ViewFactoryBean, BaseViewHolder> adapterProducer;
    private BaseQuickAdapter<SearchEntity.DataBean.ViewDistributorBean, BaseViewHolder> adapterAgency;
    public static final int REQUEST_CODE_HOME = 0;
    public static final int REQUEST_CODE_SUPPLY = 1;//供应
    public static final int REQUEST_CODE_PURCHASE = 2;//采购
    public static final int REQUEST_CODE_AGENCY = 3;
    private int info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> SearchListActivity.this.finish());
        titleBar.setText("搜索");

        info = getIntent().getIntExtra("info", REQUEST_CODE_HOME);

        tabDetail.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setDataToView(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        rvCollectionList.setItemAnimator(new DefaultItemAnimator());
        adapterInfo = new BaseQuickAdapter<SearchEntity.DataBean.ViewArticleBean, BaseViewHolder>(R.layout.item_home) {
            @Override
            protected void convert(BaseViewHolder helper, SearchEntity.DataBean.ViewArticleBean item) {
                helper.setText(R.id.tv_item_home_content, item.getContent());
                helper.setText(R.id.tv_item_home_good, item.getPraise_nums() + "");
                helper.setText(R.id.tv_item_home_watch, item.getBrowse_nums() + "");
                helper.setText(R.id.tv_item_home_location, item.getAddress_detail());
                helper.setText(R.id.tv_item_home_name, item.getUser_name());
                helper.setText(R.id.tv_item_date, item.getCreate_at());
                helper.setText(R.id.tv_item_home_type, item.getType() == 1 ? "供应" : "采购");
                helper.setBackgroundRes(R.id.tv_item_home_type, item.getType() == 1 ? R.drawable.shape_supply_bg : R.drawable.shape_purchase_bg);

                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_home_head);
                Picasso.with(SearchListActivity.this).load(item.getUser_avatar()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
                RecyclerView rvImg = (RecyclerView) helper.getView(R.id.rv_item_home_img);
                rvImg.setNestedScrollingEnabled(false);
                GridLayoutManager layoutManager = new GridLayoutManager(SearchListActivity.this, 3);
                layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                rvImg.setLayoutManager(layoutManager);
                BaseQuickAdapter<String, BaseViewHolder> adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_home_img) {
                    @Override
                    protected void convert(BaseViewHolder helper, String item) {
                        SquareImageView view = (SquareImageView) helper.getView(R.id.iv_item_img);
                        Picasso.with(SearchListActivity.this).load(item).resize(AppConstant.SCREEN_WIDTH / 3, AppConstant.SCREEN_WIDTH / 3).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).into(view);
                    }
                };
                rvImg.setItemAnimator(new DefaultItemAnimator());
                adapterImg.setNewData(item.getImgList());
                rvImg.setAdapter(adapterImg);
            }
        };
        adapterInfo.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(SearchListActivity.this, InfoDetailActivity.class);
            intent.putExtra("info", adapterInfo.getData().get(position).getArticleId() + "");
            startActivity(intent);
        });

        adapterAgency = new BaseQuickAdapter<SearchEntity.DataBean.ViewDistributorBean, BaseViewHolder>(R.layout.item_agency) {
            @Override
            protected void convert(BaseViewHolder helper, SearchEntity.DataBean.ViewDistributorBean item) {
                helper.setText(R.id.tv_item_agency_name, item.getName());
                helper.setText(R.id.tv_item_agency_content, item.getDesc() + "");
                helper.setText(R.id.tv_item_agency_brand, "经营品牌：" + (TextUtils.isEmpty(item.getBrand()) ? "" : item.getBrand()));
                helper.setText(R.id.tv_item_agency_location, item.getAddress_name());
                helper.setText(R.id.tv_item_agency_distance, "");

                ImageView head = (ImageView) helper.getView(R.id.iv_item_agency);
                Picasso.with(SearchListActivity.this).load(item.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);

                RecyclerView rvTag = (RecyclerView) helper.getView(R.id.rv_item_agency_tag);
                if (TextUtils.isEmpty(item.getChannel())) {
                    rvTag.setVisibility(View.GONE);
                } else {
                    rvTag.setVisibility(View.VISIBLE);
                    rvTag.setNestedScrollingEnabled(false);
                    LinearLayoutManager layoutManager = new LinearLayoutManager(SearchListActivity.this);
                    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    rvTag.setLayoutManager(layoutManager);
                    BaseQuickAdapter<String, BaseViewHolder> adapterImg = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_agency_tag) {
                        @Override
                        protected void convert(BaseViewHolder helper, String item) {
                            helper.setText(R.id.iv_item_tag, item);
                        }
                    };
                    rvTag.setItemAnimator(new DefaultItemAnimator());
                    String[] split = item.getChannel().split(" ");
                    adapterImg.setNewData(Arrays.asList(split));
                    rvTag.setAdapter(adapterImg);
                }
            }
        };
        adapterAgency.setOnItemClickListener((adapter, view, position) -> {
            Intent intent = new Intent(SearchListActivity.this, AgencyDetailActivity.class);
            intent.putExtra("info", ((SearchEntity.DataBean.ViewDistributorBean) adapter.getData().get(position)).getDistrId() + "");
            startActivity(intent);
        });

        adapterStore = new BaseQuickAdapter<SearchEntity.DataBean.StoreListBean, BaseViewHolder>(R.layout.item_type) {
            @Override
            protected void convert(BaseViewHolder helper, SearchEntity.DataBean.StoreListBean item) {
                helper.setText(R.id.tv_item_type_name, item.getName());
                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_type_head);
                Picasso.with(SearchListActivity.this).load(item.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
            }
        };
        adapterStore.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(SearchListActivity.this, ProducerDetailActivity.class);
            intent.putExtra("info", adapterStore.getData().get(position).getFactoryId() + "");
            startActivity(intent);
        });

        adapterProducer = new BaseQuickAdapter<SearchEntity.DataBean.ViewFactoryBean, BaseViewHolder>(R.layout.item_type) {
            @Override
            protected void convert(BaseViewHolder helper, SearchEntity.DataBean.ViewFactoryBean item) {
                helper.setText(R.id.tv_item_type_content, item.getDesc());
                helper.setText(R.id.tv_item_type_name, item.getName());
                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_type_head);
                Picasso.with(SearchListActivity.this).load(item.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
            }
        };
        adapterProducer.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(SearchListActivity.this, ProducerDetailActivity.class);
            intent.putExtra("info", adapterProducer.getData().get(position).getFactoryId() + "");
            startActivity(intent);
        });
    }

    private void setDataToView(int index) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvCollectionList.setLayoutManager(layoutManager);

        if (entity == null) {
            showToast("暂无数据");
            return;
        }

        switch (index) {
            case 0:
                rvCollectionList.setAdapter(adapterInfo);
                adapterInfo.setNewData(entity.getData().getViewArticle());
                break;
            case 1:
                rvCollectionList.setAdapter(adapterAgency);
                adapterAgency.setNewData(entity.getData().getViewDistributor());
                break;
            case 2:
                rvCollectionList.setAdapter(adapterStore);
                adapterStore.setNewData(entity.getData().getStoreList());
                break;
            case 3:
                rvCollectionList.setAdapter(adapterProducer);
                adapterProducer.setNewData(entity.getData().getViewFactory());
                break;
        }
    }

    private void getListData(String search) {
        HashMap<String, String> map = new HashMap<>();
        map.put("content", search);
        Subscription subscribe = DataCenter.searchInfo(map).subscribe(new HttpSubscriber<SearchEntity>(this, showLoading()) {

            @Override
            public void onNext(SearchEntity entity) {
                SearchListActivity.this.entity = entity;
                if (info == REQUEST_CODE_HOME) {
                    tabDetail.getTabAt(0).select();
                    tabDetail.setVisibility(View.VISIBLE);
                    setDataToView(0);
                } else if (info == REQUEST_CODE_PURCHASE) {
                    List<SearchEntity.DataBean.ViewArticleBean> viewArticle = entity.getData().getViewArticle();
                    ArrayList<SearchEntity.DataBean.ViewArticleBean> articleBeen = new ArrayList<>();
                    for (int i = 0; i < viewArticle.size(); i++) {
                        if (viewArticle.get(i).getType() == 2 && info == REQUEST_CODE_PURCHASE) {
                            articleBeen.add(viewArticle.get(i));
                        }
                    }
                    entity.getData().setViewArticle(articleBeen);
                    SearchListActivity.this.entity = entity;
                    setDataToView(0);
                } else if (info == REQUEST_CODE_SUPPLY) {
                    List<SearchEntity.DataBean.ViewArticleBean> viewArticle = entity.getData().getViewArticle();
                    ArrayList<SearchEntity.DataBean.ViewArticleBean> articleBeen = new ArrayList<>();
                    for (int i = 0; i < viewArticle.size(); i++) {
                        if (viewArticle.get(i).getType() == 1 && info == REQUEST_CODE_SUPPLY) {
                            articleBeen.add(viewArticle.get(i));
                        }
                    }
                    entity.getData().setViewArticle(articleBeen);
                    SearchListActivity.this.entity = entity;
                    setDataToView(0);
                } else if (info == REQUEST_CODE_AGENCY) {
                    setDataToView(1);
                }
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_list;
    }

    @OnClick(R.id.tv_search_start)
    public void onViewClicked() {
        if (TextUtils.isEmpty(etSearch.getText().toString())) {
            showToast("请输入关键词后搜索");
            return;
        }
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && etSearch.isFocused()) {
            imm.toggleSoftInput(0, 0);
        }
        getListData(etSearch.getText().toString());
    }
}
